package com.sailfish.springbootdemo.controller.db2;

import ch.qos.logback.core.util.FileUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.dao.db2.PcbCapacityParamVersionDao;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db2.*;
import com.sailfish.springbootdemo.service.db2.*;
import com.sailfish.springbootdemo.service.db4.UserService;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/pcbCapacityData")
public class PcbCapacityDataController {

    @Autowired
    PcbCapacityDataService pcbCapacityDataService;
    @Autowired
    PcbCapacityParamService pcbCapacityParamService;
    @Autowired
    PcbSonFactoryInfoService pcbSonFactoryInfoService;
    @Autowired
    PcbCapacityApproveDetailService pcbCapacityApproveDetailService;
    @Autowired
    PcbCapacityParamVersionService pcbCapacityParamVersionService;

    /*
    按照分级结构给出数据-批量，小批量
     */
    @PostMapping("/getAllCapacityData")
    public Result getType(Integer pcbCapacityHistoryId, Integer pcbFactoryId, String version) {
        if (StringUtils.isBlank(version)) {
            return ResultUtil.error(500, "参数version是空的", "param version is null", null);
        } else {
            final PcbCapacityParamVersion newestVersion = pcbCapacityParamService.getNewestVersion(null, 1);
            String str_newestVersion = "";
            if (newestVersion != null) {
                str_newestVersion = newestVersion.getVersionYear() + "_" + newestVersion.getVersionNum();
                if (version.equals(str_newestVersion)) {
                    List<PcbCapacityParam> allData = pcbCapacityParamService.getChildrenWithData(0, pcbCapacityHistoryId, pcbFactoryId, 1);
                    return ResultUtil.success(allData);
                } else {
                    List<PcbCapacityParamHistory> childrenWithDataHistory = pcbCapacityParamService.getChildrenWithDataHistory(0, pcbFactoryId, 1, version);
                    return ResultUtil.success(childrenWithDataHistory);
                }
            } else {
                List<PcbCapacityParam> allData = pcbCapacityParamService.getChildrenWithData(0, pcbCapacityHistoryId, pcbFactoryId, 1);
                return ResultUtil.success(allData);
            }
        }
    }

    @PostMapping("/getTemplateStatus")
    public Result getTemplateStatus() {
        String templateStatus = null;
        String sStatus = null;
        PcbCapacityDataApprove pcbCapacityDataApprove = pcbCapacityDataService.getTemplateStatus();
        if (pcbCapacityDataApprove != null) {
            templateStatus = pcbCapacityDataApprove.getApproveStatus();
//            if(templateStatus == 5){
//                sStatus= "已分发";
//            }
//            if(templateStatus == 6) {
//                sStatus = "待分发";
//            }
        }
        return ResultUtil.success(templateStatus);
    }

    /*
    按照分级结构给出数据-H3C要求值
     */
    @PostMapping("/getAllH3CRequireData")
    public Result getAllH3CRequireData(String version) {
        if (StringUtils.isBlank(version)) {
            return ResultUtil.error(500, "参数version是空的", "param version is null", null);
        } else {
            final PcbCapacityParamVersion newestVersion = pcbCapacityParamService.getNewestVersion(null, 1);
            String str_newestVersion = "";
            if (newestVersion != null) {
                str_newestVersion = newestVersion.getVersionYear() + "_" + newestVersion.getVersionNum();
                if (version.equals(str_newestVersion)) {
                    List<PcbCapacityParam> allData = pcbCapacityParamService.getChildrenWithData(0, null, null, 3);
                    return ResultUtil.success(allData);
                } else {
                    List<PcbCapacityParamHistory> childrenWithDataHistory = pcbCapacityParamService.getChildrenWithDataHistory(0, null, 3, version);
                    return ResultUtil.success(childrenWithDataHistory);
                }
            } else {
                List<PcbCapacityParam> allData = pcbCapacityParamService.getChildrenWithData(0, null, null, 3);
                return ResultUtil.success(allData);
            }
        }
    }

    /*
    只获取数据
     */
    @PostMapping("/getCapacityData")
    public Result getCapacityData(Integer pcbCapacityHistoryId, Integer pcbFactoryId, String version) {
        if (StringUtils.isBlank(version)) {
            return ResultUtil.error(500, "参数version是空的", "param version is null", null);
        } else {
            PcbCapacityParamVersion newestVersion = pcbCapacityParamService.getNewestVersion(null, 1);
            String str_newestVersion = "";
            if (newestVersion != null) {
                str_newestVersion = newestVersion.getVersionYear() + "_" + newestVersion.getVersionNum();
                if (version.equals(str_newestVersion)) {
                    List<PcbCapacityData> allData = pcbCapacityDataService.getAllData(pcbCapacityHistoryId, pcbFactoryId, 1);
                    return ResultUtil.success(allData);
                } else {
                    List<PcbCapacityDataHistory2> allData = pcbCapacityDataService.getAllDataHistory(pcbFactoryId, 1, version);
                    return ResultUtil.success(allData);
                }
            } else {
                List<PcbCapacityData> allData = pcbCapacityDataService.getAllData(pcbCapacityHistoryId, pcbFactoryId, 1);
                return ResultUtil.success(allData);
            }
        }
    }

    /*
        只获取数据
    */
    @PostMapping("/getH3CCapacityData")
    public Result getH3CCapacityData(String version) {
        if (StringUtils.isBlank(version)) {
            return ResultUtil.error(500, "参数version是空的", "param version is null", null);
        } else {
            PcbCapacityParamVersion newestVersion = pcbCapacityParamService.getNewestVersion(null, 1);
            String str_newestVersion = "";
            if (newestVersion != null) {
                str_newestVersion = newestVersion.getVersionYear() + "_" + newestVersion.getVersionNum();
                if (version.equals(str_newestVersion)) {
                    List<PcbCapacityData> allData = pcbCapacityDataService.getAllData(null, null, 3);
                    return ResultUtil.success(allData);
                } else {
                    List<PcbCapacityDataHistory2> allDataHistory = pcbCapacityDataService.getAllDataHistory(null, 3, version);
                    return ResultUtil.success(allDataHistory);
                }
            } else {
                List<PcbCapacityData> allData = pcbCapacityDataService.getAllData(null, null, 3);
                return ResultUtil.success(allData);
            }
        }
    }

    /*
        获取能力对比数据
    */
    @PostMapping("/getCapacityComparison")
    public Result getCapacityComparison(@RequestBody String data) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        JSONArray jsonArray = jsonObject.getJSONArray("factoryIds");
        List<Integer> factoryIds = JSONArray.parseArray(jsonArray.toJSONString(), Integer.class);
        String version = jsonObject.getString("version");
        if (factoryIds == null) {
            return ResultUtil.error(500, "参数为空factoryIds", "param factoryIds miss", null);
        }
        if (StringUtils.isBlank(version)) {
            return ResultUtil.error(500, "参数version是空的", "param version is null", null);
        }
        PcbCapacityParamVersion newestVersion = pcbCapacityParamService.getNewestVersion(null, 1);
        String str_newestVersion = "";
        if (newestVersion != null) {
            str_newestVersion = newestVersion.getVersionYear() + "_" + newestVersion.getVersionNum();
            if (version.equals(str_newestVersion)) {
                List<PcbCapacityParam> allData = pcbCapacityParamService.getCapacityComparison(0, null, factoryIds);
                return ResultUtil.success(allData);
            } else {
                List<PcbCapacityParamHistory> capacityComparisonHistory = pcbCapacityParamService.getCapacityComparisonHistory(0, factoryIds, version);
                return ResultUtil.success(capacityComparisonHistory);
            }
        } else {
            List<PcbCapacityParam> allData = pcbCapacityParamService.getCapacityComparison(0, null, factoryIds);
            return ResultUtil.success(allData);
        }
    }

    /*
       导出能力对比数据
    */
    @PostMapping("/outputCapacityComparison")
    public Result outputCapacityComparison(@RequestBody String data) throws IOException {
        JSONObject jsonObject = JSONObject.parseObject(data);
        Boolean isAll = jsonObject.getBoolean("isAll");
        String version = jsonObject.getString("version");
        Integer type = jsonObject.getInteger("type");//1只输出大批量，2只输出小批量，3输出大批量和小批量,4 输出厂家的大批量和小批量，H3C要求值不输出
        JSONArray jsonArray = jsonObject.getJSONArray("factoryIds");
        if (!isAll && (jsonArray == null)) {
            return ResultUtil.error(500, "参数factoryIds为空", "param factoryIds miss", null);
        }
//        if(type == null){
//            return ResultUtil.error(500,"参数type为空","param type miss",null);
//        }
        List<Integer> factoryIds;
        if (isAll) {
            factoryIds = pcbSonFactoryInfoService.getAllId();
        } else {
            factoryIds = JSONArray.parseArray(jsonArray.toJSONString(), Integer.class);
        }
        Result result;

        if (type != null && type == 4) {
            result = pcbCapacityParamService.outputCapacityComparisonFactory(0, null, factoryIds, version);
        } else {
            result = pcbCapacityParamService.outputCapacityComparison(0, null, factoryIds, version, type);
        }
        if (result.getCode().equals(200)) {
            try {
                String filepath = (String) result.getData();
                File file = new File(filepath);
                String fname = file.getName();
                byte[] bytedata = null;
                InputStream in = new FileInputStream(file);  //InputStream in = url.openStream();
                bytedata = new byte[in.available()];
                in.read(bytedata);
                in.close();
                Base64.Encoder encoder = Base64.getEncoder();
                String base64 = encoder.encodeToString(bytedata);

                Map<String, Object> map = new HashMap<>();
                map.put("base64", base64);
                map.put("fileName", fname);
                return ResultUtil.success(map);

            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
            }
        } else {
            return result;
        }
    }

    @PostMapping("/insertOrUpdate")
    public Result insertOrUpdate(@RequestBody String data) {
        return pcbCapacityDataService.insertOrUpdate(data);
    }

    @PostMapping("/deleteByFactoryId")
    public Result deleteByFactoryId(Integer pcbCapacityHistoryId, Integer pcbFactoryId) {
        return pcbCapacityDataService.delete(pcbCapacityHistoryId, pcbFactoryId);
    }

    @PostMapping("/updateApproveStatus")
    public Result updateApproveStatus(Integer id, String approveStatus, String remark) {
        return pcbCapacityDataService.updateApproveStatus(id, approveStatus, remark);
    }

    @PostMapping("/submitApprove")
    public Result submitApprove(@RequestBody String data) {
        return pcbCapacityDataService.submitApprove(data);
    }

    @PostMapping("/getApproveList")
    public Result getApproveList(Integer parentFactoryId, Integer factoryId, String approveStatus, Integer flowType, boolean isAll) {
        List<PcbCapacityDataApprove> approveList = pcbCapacityDataService.getApproveList(parentFactoryId, factoryId, approveStatus, flowType, isAll);
        return ResultUtil.success(approveList);
    }

    @PostMapping("/deleteApproveData")
    public Result deleteApproveData(Integer approveDataId) {
        final Result result = pcbCapacityDataService.deleteApproveData(approveDataId);
        return result;
    }

    @PostMapping("/getApproveProcess")
    public Result getApproveProcess(Integer dataId, Integer approveType) {
        List<PcbApproveProcess> approveList = pcbCapacityDataService.getApproveProcess(dataId, approveType);
        return ResultUtil.success(approveList);
    }

    @Value("${personal.config.file.pcb-data-template}")
    private String pcbDataTemplateUrl;

    @PostMapping("/downloadDataTemplate")
    public Result downloadDataTemplate() {
        try {
            String filepath = pcbDataTemplateUrl;
            File file = new File(filepath);
            String fname = file.getName();
            byte[] bytedata = null;
            InputStream in = new FileInputStream(file);
            bytedata = new byte[in.available()];
            in.read(bytedata);
            in.close();
            Base64.Encoder encoder = Base64.getEncoder();
            String base64 = encoder.encodeToString(bytedata);

            Map<String, Object> map = new HashMap<>();
            map.put("base64", base64);
            map.put("fileName", fname);
            return ResultUtil.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/importH3C")
    public Result importH3C(HttpServletRequest req, Integer factoryId) throws IOException {
        Result result;
        if (factoryId == null) {
            result = pcbCapacityDataService.importH3C(req, factoryId, true);
        } else {
            result = pcbCapacityDataService.importH3C(req, factoryId, false);
        }
        return result;
    }

    @PostMapping("/clearData")
    public Result clearDataByParamId(Integer paramId) {
        if (paramId == null) {
            return ResultUtil.error(500, "参数paramId为空", "paramId is null", null);
        }
        return pcbCapacityDataService.clearData(paramId);
    }

    @PostMapping("/checkHasData")
    public Result checkHasData(Integer paramId) {
        if (paramId == null) {
            return ResultUtil.error(500, "参数paramId为空", "paramId is null", null);
        }
        boolean re = pcbCapacityDataService.checkHasData(paramId);
        return ResultUtil.success(re);
    }

    @PostMapping("/checkHasSonParam")
    public Result checkHasSonParam(Integer paramId) {
        if (paramId == null) {
            return ResultUtil.error(500, "参数paramId为空", "param paramId is null", null);
        }
        boolean re = pcbCapacityParamService.checkHasSonParam(paramId);
        return ResultUtil.success(re);
    }

    @PostMapping("/checkHasDataByFactory")
    public Result checkHasDataByFactory(Integer factoryId) {
        if (factoryId == null) {
            return ResultUtil.error(500, "参数factoryId为空", "param factoryId is null", null);
        }
        boolean re = pcbCapacityDataService.checkHasDataByFactory(factoryId);
        return ResultUtil.success(re);
    }

    @PostMapping("/clearDataByFactory")
    public Result clearDataByFactory(Integer factoryId) {
        if (factoryId == null) {
            return ResultUtil.error(500, "参数factoryId为空", "param factoryId is null", null);
        }
        return pcbCapacityDataService.clearDataByFactoryId(factoryId);
    }

    /*
    获取审批详情
     */
    @PostMapping("/getApproveDeatil")
    public Result getApproveDeatil(Integer id, Integer flowType) {
        List<PcbCapacityApproveDetail> approveDeatil = pcbCapacityApproveDetailService.getApproveDetail(id, flowType);
        return ResultUtil.success(approveDeatil);
    }

    /*转交审核人*/
    @PostMapping("/changeApprover")
    public Result changeApprover(Integer id, Integer approveUserId) {
        if (id == null) {
            return ResultUtil.error(500, "参数id为空", "param id is null", null);
        }
        if (approveUserId == null) {
            return ResultUtil.error(500, "参数approveUserId为空", "param approveUserId is null", null);
        }
        return pcbCapacityApproveDetailService.changeApprover(id, approveUserId);
    }

    /*提交下一环节*/
    @PostMapping("/submitToNextNode")
    public Result submitToNextNode(@RequestBody String data) {
        Result result = pcbCapacityApproveDetailService.submitToNextNode(data);
        return result;
    }

    /*退回上一环节*/
    @PostMapping("/backToPreNode")
    public Result backToPreNode(@RequestBody String data) {
        Result result = pcbCapacityApproveDetailService.backToPreNode(data);
        return result;
    }

    @PostMapping("/createApproveTask")
    public Result createApproveTask(@RequestBody String data) {
        return pcbCapacityApproveDetailService.createApproveTask(data);
    }

    @PostMapping("/deleteHistoryDataAndTemplate")
    public Result deleteHistoryDataAndTemplate(String version) {
        return pcbCapacityParamService.deleteHistoryTemplate(version);
    }


}
